<template>
  <div class="hm-input">
    <input
      class="inp"
      :class="btnClass"
      :type="type"
      :value="value"
      @input="handleInput"
      :placeholder="placeholder">
    <span class="tips" v-show="isShowTips">{{ errMsg }}</span>
  </div>
</template>

<script>
export default {
  props: {
    type: {
      type: String,
      default: 'text'
    },
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    rules: {
      type: RegExp
    },
    errMsg: {
      type: String
    }
  },

  data () {
    return {
      status: ''
    }
  },

  created () {
    this.$bus.$on('btnClick', () => {
      if (this.rules) {
        this.status = this.rules.test(this.value)
      }
    })
  },

  methods: {
    handleInput (e) {
      const inpValue = e.target.value
      this.$emit('input', inpValue)
      if (this.rules) {
        this.status = this.rules.test(inpValue)
      }
    }
  },

  computed: {
    isShowTips () {
      if (this.status === '') return
      return !this.status && this.errMsg
    },
    btnClass () {
      if (this.status === '') return ''
      return this.status ? 'success' : 'error'
    }
  }
}
</script>

<style lang="scss" scoped>
.hm-input {
  position: relative;
  padding-bottom: 20px;
}

.inp {
  width: 100%;
  height: 40px;
  font-size: 18px;
  background-color: transparent;
  border-bottom: 1px solid #666;
  &.success {
    border-color: green;
  }
  &.error {
    border-color: #bd401e;
  }
}

.tips {
  position: absolute;
  left: 0;
  bottom: 0;
  color: #bd401e;
}
</style>
